package linc.cool.helloworld;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import linc.cool.utils.RabbitConstant;
import linc.cool.utils.RabbitUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.*;

/**
 * @author yqlin
 * @date 2022/3/3 5:07 上午
 * @description
 */
@Slf4j
public class Producer {
    static ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 100, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) throws IOException, TimeoutException {
        // 获取TCP长连接
        Connection connection = RabbitUtils.getConnection();
        // 创建通信通道,相当于TCP中的虚拟连接
        Channel channel = connection.createChannel();
        // 创建队列(队列ID,是否持久化,是否队列私有化,是否自动删除,其他参数)
        channel.queueDeclare(RabbitConstant.QUEUE_HELLO_WORLD, false, false, false, null);
        for (int i = 0; i < 10000; i++) {
            int finalI = i;
            executor.execute(() -> {
                try {
                    String message = "hello world" + finalI;
                    // 发信息(交换机,队列ID,其他参数,消息字节数组)
                    channel.basicPublish("", RabbitConstant.QUEUE_HELLO_WORLD, null, message.getBytes());
                    log.info("已经发送: {}", message);
                } catch (IOException e) {
                    log.error("thread internal exception: {}", e.getMessage(), e);
                }
            });
        }
        channel.close();
        connection.close();
    }
}
